package com.mox.enterprise.util;

import lombok.extern.slf4j.Slf4j;
import org.yaml.snakeyaml.Yaml;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author mox
 * @time 2020/2/17 22:07
 */

@Slf4j
public class YamlReader {

    public static Map load(String fileName) throws IOException {
        InputStream ins = null;
        HashMap properties = null;
        try {
            Yaml yaml = new Yaml();

            if (YamlReader.class.getClassLoader().getResourceAsStream(fileName) != null) {
                ins = YamlReader.class.getClassLoader().getResourceAsStream(fileName);
                log.info("读取内部yaml配置文件");
            } else {
                String path = "/properties/" + fileName;
                File file = new File(path);
                if (!file.exists()) {
                    log.error("配置文件不存在");
                }
                ins = new FileInputStream(file);
                log.info("读取外部yaml配置文件");
            }

            properties = yaml.loadAs(ins, HashMap.class);
            log.info("yaml配置信息:{}", properties);
        } catch (Exception e) {
            log.error("yaml文件读取出错:{}", e.getMessage());
        } finally {
            if (ins != null) {
                ins.close();
            }
        }
        return properties;
    }

}
